package com.example.mybaseapp.widget.my_circle_seekbar

import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Path
import android.graphics.Rect
import android.view.View
import kotlin.math.cos
import kotlin.math.sin
import kotlin.math.sqrt
import kotlin.properties.Delegates

/**
 * 绘制工具
 */
class DrawUtil(val view: View, val circleUtil: CircleUtil) {
    /**
     * 指针所在的角度
     */
     var selectDegree = 100F
    /**当前的刻度（用来和刻度位置的判断）*/
     var currentSelectDegree = 100F

    /**三角形（指针）底部宽*/
     var selectWidth = 20F
    /**三角形（指针）高度*/
     var selectHeight = 30F


    /**圆心X*/
    var centerX by Delegates.notNull<Float>()
    /**圆心Y*/
    var centerY by Delegates.notNull<Float>()
    /**半圆的角度，这个是根据控件大小，动态获取的*/
    var radius = 0f
    /**
     * 刻度线距离圆的padding距离
     */
    var distanceFromEdge = 25F
    var MotionEvent_Line_ACTION_DOWN = false
    var MotionEvent_Line_ACTION_UP = false
    var MotionEvent_Line_ACTION_MOVE = false
    /**指针的触控标志位*/
    var MotionEvent_Select_Line_ACTION_DOWN = false
    /**指针的触控标志位*/
    var MotionEvent_Select_Line_ACTION_UP = false
    var MotionEvent_Select_Line_ACTION_MOVE = false

    /**设置标志，是否要在放手后，对准刻度 true-是*/
    var needAutoMoveAfterTouchUp = false

    /**三角形（指针）顶部坐标X*/
     var selectTopX by Delegates.notNull<Float>()
    /**三角形（指针）顶部坐标Y*/
     var selectTopY by Delegates.notNull<Float>()
    /**三角形（指针）底部坐标X*/
      var selectBottomX by Delegates.notNull<Float>()
    /**三角形（指针）底部坐标Y*/
      var selectBottomY by Delegates.notNull<Float>()

    private var pointTmpAX:Float by Delegates.notNull()
    private var pointTmpAY:Float by Delegates.notNull()
    private var pointTmpBX:Float by Delegates.notNull()
    private var pointTmpBY:Float by Delegates.notNull()
    /**长的刻度线的长度*/
    private var longLineSize = 50F
    /**短的刻度线的长度*/
    private var shortLineSize = longLineSize/2

    /**
     * 画半圆
     */
    fun drawableHalfCircle(canvas: Canvas, halfCircleStartAngle:Float, halfCircleSweepAngle:Float, paint:Paint) {
        canvas.drawArc(centerX - radius, centerY - radius, centerX + radius, centerY + radius,
            halfCircleStartAngle, halfCircleSweepAngle, true, paint) // 绘制半圆形
        canvas.save()
    }

    /**
     * 画各种刻度线
     */
    fun drawableLine(canvas: Canvas,points:MutableList<PointsData>,touchDegree:Float,
                     lineRedPaint:Paint,linePaint: Paint) {
        if(MotionEvent_Line_ACTION_UP){//放手后保存状态
            circleUtil.isUpNow = true
            if(needAutoMoveAfterTouchUp){//自动对准
                println("drawableLine 放手后自动校准 ${circleUtil.upMoveDegreeRange}")
//                circleUtil.endMoveState()
                for (n in 0 until points.size) {
                    points[n].degree = circleUtil.degreeSub(points[n].degree,touchDegree,circleUtil.upMoveDegreeRange)
                }
                circleUtil.upMoveDegreeRange = 0F
                refreshEvent()
                view.invalidate()
                return
            }
            for (n in 0 until points.size ){
//            通过弧度来计算位置
                points[n].degree = circleUtil.degreeSub(points[n].degree,touchDegree)
                drawLineFromCenter(canvas, points[n], points[n].degree, n%3==0,
                      lineRedPaint, linePaint)
            }
            refreshEvent()
        }else if(MotionEvent_Line_ACTION_MOVE){//触摸的时候，滑动
            for (n in 0 until points.size ){
                println("LongLine Degree： ${points[n].degree - touchDegree}")
                //            通过弧度来计算位置
                drawLineFromCenter(canvas,points[n],circleUtil.degreeSub(points[n].degree , touchDegree),  n%3==0,
                      lineRedPaint, linePaint)
            }
        }else{//平常没滑动的绘制
            for (n in 0 until points.size){
                //            通过弧度来计算位置
                drawLineFromCenter(canvas,points[n], points[n].degree,  n%3==0,
                      lineRedPaint, linePaint)
            }
        }
    }

    /**
     * 绘制单个线条
     * @param text 刻度
     * @param angleRadians 弧度
     * @param isLong 是否是长的
     */
    private fun drawLineFromCenter(
        canvas: Canvas,
        text: PointsData,
        angleDegree: Float,
        isLong: Boolean,
        lineRedPaint:Paint,linePaint: Paint
    ) {
        val angleRadians = Math.toRadians(angleDegree.toDouble()).toFloat()
        pointTmpAX = centerX + (radius - distanceFromEdge) * cos(angleRadians)
        pointTmpAY = centerY - (radius - distanceFromEdge) * sin(angleRadians)
        if(isLong) {
            pointTmpBX = centerX + (radius - distanceFromEdge - longLineSize) * cos(angleRadians)
            pointTmpBY = centerY - (radius - distanceFromEdge - longLineSize) * sin(angleRadians)
            if(circleUtil.areDegreesClose(angleDegree,currentSelectDegree)){
                circleUtil.hasSelectListener(text)
                drawLongLine(canvas, text.value, angleRadians,lineRedPaint)
            }else{
                drawLongLine(canvas, text.value, angleRadians,linePaint)
            }
        }else{
            pointTmpBX = centerX + (radius - distanceFromEdge - shortLineSize) * cos(angleRadians)
            pointTmpBY = centerY - (radius - distanceFromEdge - shortLineSize) * sin(angleRadians)
            if(circleUtil.areDegreesClose(angleDegree,currentSelectDegree)){
                circleUtil.hasSelectListener(text)
                canvas.drawLine(pointTmpAX,pointTmpAY,pointTmpBX,pointTmpBY,lineRedPaint)
            }else{
                canvas.drawLine(pointTmpAX,pointTmpAY,pointTmpBX,pointTmpBY,linePaint)
            }
        }
    }

    private fun drawLongLine(
        canvas: Canvas,
        text: Any,
        angleRadians: Float,
        mPaint: Paint
    ) {
        canvas.drawLine(pointTmpAX, pointTmpAY, pointTmpBX, pointTmpBY, mPaint)

        //    ----绘制文字
        val rectF = Rect()
        mPaint.getTextBounds(text.toString(), 0, text.toString().length, rectF)
        // 获取文字的宽度和高度
        val textWidth = mPaint.measureText(text.toString())
        val textHeight = mPaint.fontMetrics.bottom - mPaint.fontMetrics.top
        println("textHeight=$textHeight textWidth=$textWidth")
        // 计算文字位置
        val textX =
            centerX + (radius - distanceFromEdge - longLineSize - textHeight) * cos(angleRadians)
        val textY =
            centerY - (radius - distanceFromEdge - longLineSize - textHeight) * sin(angleRadians)
        // 计算文字的基准位置  如果文字要朝向圆心，需要在这里实现
        // 绘制刻度文字
        canvas.drawText(text.toString(), textX, textY, mPaint)
    }

    fun drawableSelectLine(canvas: Canvas,touchDegree:Float,view: View,pathPaint: Paint) {
        if(MotionEvent_Select_Line_ACTION_MOVE){//触摸的滑动
            currentSelectDegree = selectDegree - touchDegree
            drawableTriangle(canvas, currentSelectDegree, pathPaint)
            if(MotionEvent_Select_Line_ACTION_UP) {//放手后，保存角度
                selectDegree-= touchDegree
                currentSelectDegree = selectDegree
                circleUtil.isUpNow = true
                if(needAutoMoveAfterTouchUp) {//对准刻度
//                    circleUtil.endMoveState()
                    selectDegree += circleUtil.upMoveDegreeRange
                    currentSelectDegree = selectDegree
                    println("selectAngelRadians=$selectDegree")
                    refreshEvent()
                    view.invalidate()
                }else{
                    refreshEvent()
                    view.invalidate()
                }
            }
        }else{//平常的滑动
            drawableTriangle(canvas, selectDegree, pathPaint)
        }
    }

    /**
     * 绘制三角形
     */
    fun drawableTriangle(
        canvas: Canvas,
        angelDegree: Float,
        pathPaint:Paint
    ) {
        val angelRadians = Math.toRadians(angelDegree.toDouble()).toFloat()
        // 假设已经获取到底部中心坐标(bottomCenterX, bottomCenterY)，顶部坐标(topX, topY)和底部宽度(width)
        selectBottomX = (centerX + (radius - distanceFromEdge) * cos(angelRadians))
        selectBottomY = (centerY - (radius - distanceFromEdge) * sin(angelRadians))
        selectTopX = (centerX + (radius - distanceFromEdge - selectHeight) * cos(angelRadians))
        selectTopY = (centerY - (radius - distanceFromEdge - selectHeight) * sin(angelRadians))

        // 计算底部中心点到顶部点的向量
        val dx = selectTopX - selectBottomX
        val dy = selectTopY - selectBottomY

// 归一化向量
        val length = sqrt(dx * dx + dy * dy) // 向量长度
        val nx = dy / length // 单位向量的x分量
        val ny = -dx / length // 单位向量的y分量

// 计算底部左边点和底部右边点的坐标
        val bottomLeftX = selectBottomX + nx * (selectWidth / 2)
        val bottomLeftY = selectBottomY + ny * (selectWidth / 2)

        val bottomRightX = selectBottomX - nx * (selectWidth / 2)
        val bottomRightY = selectBottomY - ny * (selectWidth / 2)

        val path = Path()
        path.moveTo(bottomLeftX, bottomLeftY) // 移动到底部左侧点
        path.lineTo(selectTopX, selectTopY) // 从底部左侧点到顶部点
        path.lineTo(bottomRightX, bottomRightY) // 从顶部点到底部右侧点
        path.close() // 封闭路径，形成三角形
// 绘制三角形
        canvas.drawPath(path, pathPaint)
        canvas.save()
    }



    /**
     * 刷新事件状态
     */
    fun refreshEvent() {
        MotionEvent_Line_ACTION_DOWN = false
        MotionEvent_Line_ACTION_UP = false
        MotionEvent_Select_Line_ACTION_UP = false
        MotionEvent_Select_Line_ACTION_DOWN = false
        MotionEvent_Line_ACTION_MOVE = false
        MotionEvent_Select_Line_ACTION_MOVE = false
    }
}